package cn.tedu.oa_system.service.impl;

import cn.tedu.oa_system.base.json_result.ResultDataDto;
import cn.tedu.oa_system.base.json_result.ResultDto;
import cn.tedu.oa_system.mapper.PositionMapper;
import cn.tedu.oa_system.pojo.Dept;
import cn.tedu.oa_system.pojo.Position;
import cn.tedu.oa_system.pojo.in.PositionIn;
import cn.tedu.oa_system.service.PositionService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

import static cn.tedu.oa_system.base.constant.DataBaseConstants.DATABASE_AFFECTED_ROW;

/**
 * @Author MW
 * @Description 职位服务接口实现
 * @CreateDate 2023/1/5
 */
@Slf4j
@Service
@Transactional
public class PositionServiceImpl implements PositionService {

    @Autowired
    PositionMapper mapper;

    @Override
    public ResultDataDto<Position> list() {
        LambdaQueryWrapper<Position> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(Position::getPositionId,-1);
        List<Position> positions = mapper.selectList(queryWrapper);
        ResultDataDto<Position> resultDataDto = new ResultDataDto<>();
        resultDataDto.setDataList(positions);
        resultDataDto.setIsSuccess(true);
        return resultDataDto;
    }

    @Override
    public ResultDto<Void> addNewPosition(PositionIn positionIn) {
        log.info("正在尝试添加的职位信息：[{}]",positionIn);
        LambdaQueryWrapper<Position> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Position::getName,positionIn.getName());
        Integer i = mapper.selectCount(queryWrapper);
        Assert.isTrue(i==1,"该职位已存在,请稍后重试");
        Position position=new Position();
        BeanUtils.copyProperties(positionIn,position);
        int row = mapper.insert(position);
        Assert.isTrue(row==DATABASE_AFFECTED_ROW,"新增职位失败，请稍后重试");
        ResultDto<Void> resultDto=new ResultDto<>();
        resultDto.setIsSuccess(true);
        resultDto.setMes("添加职位成功");
        return resultDto;
    }

    @Override
    public ResultDto<Void> updatePosition(PositionIn positionIn) {
        log.info("正在尝试更改的职位信息：[{}]",positionIn);
        Position position=new Position();
        BeanUtils.copyProperties(positionIn,position);
        int row = mapper.updateById(position);
        Assert.isTrue(row==DATABASE_AFFECTED_ROW,"修改职位失败，请稍后重试");
        ResultDto<Void> resultDto=new ResultDto<>();
        resultDto.setIsSuccess(true);
        resultDto.setMes("修改职位成功");
        return resultDto;
    }
}
